import { Injectable, Inject } from '@angular/core';

import { IApiRequest } from 'interface/IApiRequest';
import { HttpService } from 'service/HttpService';
import { QuoteBasic } from 'service/QuoteBasic';

import { ProductMeta } from 'model/ProductMeta';
import { NewsMeta } from 'model/NewsMeta';
import { NewsBases } from 'model/NewsBases';
import { News } from 'model/News';

import {
  HTTP_URL,
  AUTH_URL,
  BASE_API,
  HTTP_SUCCESS
} from "utils/index";

@Injectable()
export class ApiRequest implements IApiRequest {
  apiToUrl = null;
  baseurl: string;
  authUrl: string;

  constructor(private httpService: HttpService) {

  }

  async getSelfUserProfileForManage() {
    if(!this.apiToUrl){
      await this.httpService.get(`${HTTP_URL}${BASE_API}`).then((data) => {
        this.apiToUrl = data;
      }).catch(e => {
        console.log("ApiRequest: init", e);
      });
    }
    return this.httpService.get(`${AUTH_URL}${this.apiToUrl.GetSelfUserProfileForManage}`);
  }

  async init(): Promise<boolean> {
    let flag = false;
    if(!this.apiToUrl){
      await this.httpService.get(`${HTTP_URL}${BASE_API}`).then((data) => {
        this.apiToUrl = data;
        flag = true;
      }).catch(e => {
        flag = false;
        console.log("ApiRequest: init", e);
      });
    }
    return flag;
  }

  async updateAvatar(avatarBase64): Promise<any> {
    let params = avatarBase64.substring(avatarBase64.indexOf('base64,') + 7,avatarBase64.length);
    params = `'${params}'`;

    return this.httpService.post(`${HTTP_URL}${this.apiToUrl.UpdateAvatar}`, params);
  }

  async updateUserProfile(userInfo): Promise<any> {
    let params = {
      UserId: userInfo.Id,
      UserName: userInfo.UserName,
      PhoneNumber: userInfo.PhoneNumber,
      NickName: userInfo.NickName,
      Gender: userInfo.Gender,
      Email: userInfo.Email,
      RoleId: userInfo.Role.Id,
      Password: '',
      Abstract: userInfo.Abstract
    };

    return this.httpService.post(`${HTTP_URL}${this.apiToUrl.UpdateUserProfile}`, params);
  }

  async isPhoneNumberUsed(PhoneNumber): Promise<any> {
    return this.httpService.get(`${HTTP_URL}${this.apiToUrl.IsPhoneNumberUsed}`, { PhoneNumber });
  }

  async registerByPhoneNumber(registerInfo): Promise<any> {
    return this.httpService.post(`${HTTP_URL}${this.apiToUrl.RegisterByPhoneNumber}`, registerInfo);
  }

  async requestVerificationCodeForRegister(PhoneNumber): Promise<any> {
    return this.httpService.post(`${HTTP_URL}${this.apiToUrl.RequestVerificationCodeForRegister}`, `'${PhoneNumber}'`);
  }

  async requestVerificationCodeForResetPassword(PhoneNumber): Promise<any> {
    return this.httpService.post(`${HTTP_URL}${this.apiToUrl.RequestVerificationCodeForResetPassword}`, `'${PhoneNumber}'`);
  }

  async validateVerificationCodeForResetPassword(validateTelInfo): Promise<any> {
    return this.httpService.post(`${HTTP_URL}${this.apiToUrl.ValidateVerificationCodeForResetPassword}`, validateTelInfo);
  }

  async resetPasswordByPhoneNumber(resetInfo): Promise<any> {
    return this.httpService.post(`${HTTP_URL}${this.apiToUrl.ResetPasswordByPhoneNumber}`, resetInfo);
  }

  async getHistoricalQuote(symbol: string, interval: number, sTime: number, eTime: number, maxCount: number = 1000): Promise<QuoteBasic> {
    const params = {
      symbol: symbol,
      interval: interval,
      startTimeUtc: sTime,
      endTimeUtc: eTime,
      maxCount: maxCount
    };

    let quoteBasic: QuoteBasic;

    await this.httpService.get(`${HTTP_URL}${this.apiToUrl.GetHistoricalQuote}`, params).then((data) => {
      const time = data['Time'].map(item => item * 1000);
      quoteBasic = new QuoteBasic(data['Symbol'], data['Interval'], time, data['Open'], data['Low'], data['High'], data['Close']);
    }).catch(e => {
      console.log("APIRequest: getHistoricalQuote", e);
    });

    return quoteBasic;
  }

  async getProductMeta(categoryId: number = null, language: string = null): Promise<Array<ProductMeta>> {
    const params = {
      categoryId: categoryId,
      language: language
    };

    let list: Array<any>;

    await this.httpService.get(`${HTTP_URL}${this.apiToUrl.GetProductMeta}`, params).then((data) => {
      list = <Array<ProductMeta>>data;
    }).catch(e => {
      console.log("ApiRequest: GetProductMeta", e);
    });

    return list;
  }


  async getNewsMeta(): Promise<Array<NewsMeta>> {
    let list: Array<NewsMeta> = [];

    await this.httpService.get(`${HTTP_URL}${this.apiToUrl.GetNewsMeta}`).then((data) => {
      list = <Array<NewsMeta>>data;
    }).catch(e => {
      console.log("ApiRequest: getNewsMeta", e);
    });

    return list;
  }

  async getCalendarMeta() {
    return this.httpService.get(`${HTTP_URL}${this.apiToUrl.GetCalendarMeta}`);
  }

  async getNewsBases(categoryId: string, startTimeUtc: number = 0, endTimeUtc: number = new Date().valueOf(), maxCount: number = 16): Promise<Array<NewsBases>> {
    const params = {
      categoryId: categoryId,
      startTimeUtc: startTimeUtc,
      endTimeUtc: endTimeUtc,
      maxCount: maxCount
    };

    let list: Array<NewsBases> = null;

    await this.httpService.get(`${HTTP_URL}${this.apiToUrl.GetNewsBases}`, params).then((data) => {
      list = <Array<NewsBases>>data;
    });

    return list;
  }

  async getNews(id: string): Promise<News> {
    const params = {
      id: id
    };

    let news;

    await this.httpService.get(`${HTTP_URL}${this.apiToUrl.GetNews}`, params).then((data) => {
      news = data;
    });
    return news;
  }

  async getCalendarData(start, end, productId) {
    const params = {
      startTimeUtc: start,
      endTimeUtc: end,
      productId: productId
    };

    let list;

    await this.httpService.get(`${HTTP_URL}${this.apiToUrl.GetCalendarDataAndEvent}`, params).then((data) => {
      list = data;
    });
    return list;
  }

  async getCalendarReserveOrder(categoryId, start, end, maxCount = 50) {
    const params = {
      categoryId: categoryId,
      startTimeUtc: start,
      endTimeUtc: end,
      maxCount: maxCount
    };

    let list;

    await this.httpService.get(`${HTTP_URL}${this.apiToUrl.GetCalendarReserveOrder}`, params).then((data) => {
      list = data;
    });

    return list;
  }
}
